using System.Linq;
using System.Web.Routing;
using JetBrains.Annotations;
using Dyn.News.Models;
using Dyn.News.Services;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Core.Common.Models;
using Orchard.Core.Routable.Models;
using Orchard.Data;

namespace Dyn.News.Handlers {
    [UsedImplicitly]
    public class ArticlePartHandler : ContentHandler {
        private readonly ICategoryervice _Categoryervice;
        private readonly IArticleService _ArticleService;

        public ArticlePartHandler(IRepository<ArticlePartRecord> repository)
        {
            Filters.Add(StorageFilter.For(repository));
        }
        public ArticlePartHandler(IRepository<ArticlePartRecord> repository, ICategoryervice Categoryervice, IArticleService ArticleService, RequestContext requestContext)
        {
            _Categoryervice = Categoryervice;
            _ArticleService = ArticleService;

            Filters.Add(StorageFilter.For(repository));

               
            OnGetEditorShape<ArticlePart>(SetModelProperties);
            OnUpdateEditorShape<ArticlePart>(SetModelProperties);
          
            OnCreated<ArticlePart>((context, part) => UpdateArticleCount(part));
            OnPublished<ArticlePart>((context, part) => UpdateArticleCount(part));
            OnUnpublished<ArticlePart>((context, part) => UpdateArticleCount(part));
            OnVersioned<ArticlePart>((context, part, newVersionPart) => UpdateArticleCount(newVersionPart));
            OnRemoved<ArticlePart>((context, part) => UpdateArticleCount(part));

            OnRemoved<NewsCategoryPart>(
                (context, b) =>
                ArticleService.Get(context.ContentItem.As<NewsCategoryPart>()).ToList().ForEach(
                    Article => context.ContentManager.Remove(Article.ContentItem))); 
            OnGetDisplayShape<ArticlePart>((context, article)=>{
                context.Shape.Sumary = article.Sumary;
                context.Shape.Author = article.Author;
                context.Shape.Visited = article.Visited;
            });

        }

        private void UpdateArticleCount(ArticlePart ArticlePart) {
            CommonPart commonPart = ArticlePart.As<CommonPart>();
            if (commonPart != null &&
                commonPart.Record.Container != null) {

                    NewsCategoryPart CategoryPart = ArticlePart.CategoryPart ?? 
                    _Categoryervice.Get(commonPart.Record.Container.Id, VersionOptions.Published).As<NewsCategoryPart>();

                // Ensure the "right" set of published posts for the category is obtained
                CategoryPart.ContentItem.ContentManager.Flush();
                CategoryPart.PostCount = _ArticleService.Get(CategoryPart, VersionOptions.Published).Count();
            }
        }

        private static void SetModelProperties(BuildShapeContext context, ArticlePart Article) {
            context.Shape.Category = Article.CategoryPart;
        }

        protected override void GetItemMetadata(GetContentItemMetadataContext context) {
            var Article = context.ContentItem.As<ArticlePart>();
            
            if (Article == null)
                return;

            context.Metadata.CreateRouteValues = new RouteValueDictionary {
                {"Area", "Dyn.News"},
                {"Controller", "ArticleAdmin"},
                {"Action", "Create"},
                {"categoryID", Article.CategoryPart.Id}
            };
            context.Metadata.EditorRouteValues = new RouteValueDictionary {
                {"Area", "Dyn.News"},
                {"Controller", "ArticleAdmin"},
                {"Action", "Edit"},
                {"articleId", context.ContentItem.Id},
                {"categoryID", Article.CategoryPart.Id}
            };
            context.Metadata.RemoveRouteValues = new RouteValueDictionary {
                {"Area", "Dyn.News"},
                {"Controller", "ArticleAdmin"},
                {"Action", "Delete"},
                {"articleId", context.ContentItem.Id},
                {"categoryPath", Article.CategoryPart.As<RoutePart>().Path}
            };
        }
    }
}